from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView, GenericAPIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework_jwt.settings import api_settings

from .exceptions import QQAPIError
from .serializer import QQUserSerializer
from .utils import OAuthQQ
from .models import OAuthQQUser


# GET /oauth/qq/authorization/?next=xxx
class AuthorozationView(APIView):
    def get(self, request):
        next_url = request.query_params.get('next', '/')
        print(next_url)
        oauthqq = OAuthQQ(state=next_url)
        login_url = oauthqq.get_login_url()
        return Response({"login_url": login_url})


# GET /oauth/qq/user/?code=xxx
class QQAuthUserView(GenericAPIView):
    serializer_class = QQUserSerializer

    def get(self, request):
        # 获取Authorization Code
        code = request.query_params.get('code')
        if not code:
            return Response({"message": "缺少code参数"}, status=status.HTTP_400_BAD_REQUEST)
        # 通过Authorization Code获取Access Token
        oauthqq = OAuthQQ()
        try:
            access_token = oauthqq.get_access_token(code)
            print(access_token)
            # 获取用户OpenID
            open_id = oauthqq.get_openid(access_token)
            print(open_id)
        except QQAPIError:
            return Response({"message": "QQ服务器错误"}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
        try:
            oauthqq_user = OAuthQQUser.objects.get(openid=open_id)
        except OAuthQQUser.DoesNotExist:
            token = oauthqq.generate_save_user_token(open_id)
            return Response({"access_token": token})
        else:
            user = oauthqq_user.user
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            user.token = token
            res_data = {
                'user_id': user.id,
                'username': user.username,
                'token': token
            }
            return Response(res_data)

    # def post(self, request, *args, **kwargs):
    #     print(1)
    #     return self.create(request)

    def post(self, request):
        print(request.data)
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
